import { Component, EventEmitter, Injector, Output, ViewChild } from '@angular/core';
import { JsonEditorComponent, JsonEditorOptions } from '@app/shared/common/json-editor/json-editor.component';
import { HttpClient} from '@angular/common/http';
import { AppConsts } from '@shared/AppConsts';
import { CustomConfigServiceProxy, IEntityDtoOfGuid, NameValue, PagedCustomConfigDto, PageViewServiceProxy, SetStatusInput } from '@shared/service-proxies/service-proxies';
import { ModalDirective } from 'ngx-bootstrap/modal';
import { finalize } from 'rxjs/operators';
import { AppModalComponentBase } from '@shared/common/app-modal-component-base';
import { LazyLoadEvent } from 'primeng/api';
import { Table } from 'primeng/table';
import { Paginator } from 'primeng/paginator';
import { CreateOrEditPageViewModalComponent } from './create-or-edit-pageview-modal.component';
import { CopyPageViewModalComponent } from './copy-pageview-modal.component';

@Component({
    selector: 'pageview-modal',
    templateUrl: './pageview-modal.component.html'
})
export class PageViewModalComponent extends AppModalComponentBase {
    
    @ViewChild('dataTable', { static: true }) dataTable: Table;
    @ViewChild('paginator', { static: true }) paginator: Paginator;
    @ViewChild('createOrEditPageViewModal', { static: true }) createOrEditPageViewModal: CreateOrEditPageViewModalComponent;
    @ViewChild('copyPageViewModal', { static: true }) copyPageViewModal: CopyPageViewModalComponent;

  
    @ViewChild('modal', { static: true }) modal: ModalDirective;
    @Output() callback: EventEmitter<any> = new EventEmitter<any>();

    filterText = '';
    selectedDatas: IEntityDtoOfGuid[];
    loading = false;

    title: string;
    frontendPageId: string = null;

    constructor(
        injector: Injector,
        private _pageViewServiceProxy: PageViewServiceProxy
    ) {
        super(injector);
    }


    show(frontendPageId: string, title: string) {
        this.frontendPageId = frontendPageId;
        this.title = title;
        this.modal.show();

        this.getListData(null);
    }

    getListData(event?: LazyLoadEvent) {
        if (this.primengTableHelper.shouldResetPaging(event)) {
            if (this.primengTableHelper.TryChangePage(this.paginator, 0)) {
                return;
            }
        }

        this.selectedDatas = [];

        this.primengTableHelper.showLoadingIndicator();
        this._pageViewServiceProxy.getPagedPageViews(
            this.frontendPageId,
            this.filterText,
            this.primengTableHelper.getSorting(this.dataTable),
            this.primengTableHelper.getMaxResultCount(this.paginator, event),
            this.primengTableHelper.getSkipCount(this.paginator, event)
        ).pipe(finalize(() => this.primengTableHelper.hideLoadingIndicator()))
        .subscribe(result => {
            this.primengTableHelper.totalRecordsCount = result.totalCount;
            this.primengTableHelper.records = result.items;
            this.primengTableHelper.hideLoadingIndicator();
        });
    }

    reloadPage() {
        if (this.primengTableHelper.TryChangePage(this.paginator, this.paginator.getPage())) {
            return;
        }

        this.getListData(null);
    }

    close(): void {
        this.modal.hide();
    }

    edit(entry) {
        this.openCreateOrEdit(entry);
    };
    createNews() {
        this.openCreateOrEdit(null);
    }

    delete() {
        if (!this.selectedDatas) return;
        let ids = this.selectedDatas.map(item => item.id);
        if (ids.length == 0) return;
        this.message.confirm(this.l('DeleteWarningMessage'), this.l('AreYouSure'),
            (isConfirmed) => {
                if (!isConfirmed) return;
                this._pageViewServiceProxy.deleteList(ids)
                    .subscribe(() => {
                        this.selectedDatas = [];
                        this.reloadPage();
                        this.notify.success(this.l('SuccessfullyDeleted'));
                    });
            })
    }

    deleteSingle(entity) {
        this.message.confirm(this.l('DeleteWarningMessage'), this.l('AreYouSure'),
            (isConfirmed) => {
                if (!isConfirmed) return;
                this._pageViewServiceProxy.delete(entity.id)
                    .subscribe(() => {
                        this.selectedDatas = [];
                        this.reloadPage();
                        this.notify.success(this.l('SuccessfullyDeleted'));
                    });
            })
    }


    changeState(state: boolean) {
        if (!this.selectedDatas) return;
        let ids = this.selectedDatas.map(item => item.id);

        if (ids.length > 0) {
            let msg: string;
            if (state) {
                msg = this.l('ReleaseWarningMessage');
            }
            else {
                msg = this.l('UndoReleaseWarningMessage');
            }
            this.message.confirm(msg, this.l('AreYouSure'),
                (isConfirmed) => {
                    if (!isConfirmed) return;

                    let input = new SetStatusInput();
                    input.idList = ids;
                    input.isActive = state;

                    this._pageViewServiceProxy.setStatus(input)
                        .subscribe(() => {
                            this.selectedDatas = [];
                            this.getListData(null);
                            if (state) {
                                this.notify.success(this.l('ReleaseSuccessfully'));
                            } else {
                                this.notify.success(this.l('CancelReleaseSuccessfully'));
                            }
                        });
                })
        }
    }

    openCreateOrEdit(entry) {
        if (entry) {
            this.createOrEditPageViewModal.show(entry.id, this.frontendPageId);
        } else {
            this.createOrEditPageViewModal.show(null, this.frontendPageId);
        }
    }

    copyViews() {
        if (!this.selectedDatas) return;
        let ids = this.selectedDatas.map(item => item.id);
    }
    copyViewsCallback(page: any){
        this.frontendPageId = page.pageId;
        if (this.primengTableHelper.TryChangePage(this.paginator, 0)) {
            return;
        }

        this.getListData(null);
    }
}
